package net.lab1024.robot;

import net.lab1024.robot.type.DingTalkRobotMsgMarkdown;
import net.lab1024.util.HttpClientUtil;
import net.lab1024.util.StringUtil;
import org.apache.http.client.HttpClient;

/**
 * DingTalkRobotNotify builder
 *
 * @author listen
 * @date 2019/07/17 11:17
 */
public class DingTalkRobotNotifyBuilder {

    private static final String DEFAULT_DING_TALK_URL = "https://oapi.dingtalk.com/robot/send?access_token=";

    private String dingTalkUrl;

    private String robotAccessToken;

    private String secret;

    private HttpClient httpClient;

    public DingTalkRobotNotifyBuilder setDingTalkUrl(String dingTalkUrl) {
        this.dingTalkUrl = dingTalkUrl;
        return this;
    }

    public DingTalkRobotNotifyBuilder setRobotAccessToken(String robotAccessToken) {
        this.robotAccessToken = robotAccessToken;
        return this;
    }

    public DingTalkRobotNotifyBuilder setHttpClient(HttpClient httpClient) {
        this.httpClient = httpClient;
        return this;
    }

    public DingTalkRobotNotifyBuilder setSecret(String secret) {
        this.secret = secret;
        return this;
    }

    public static DingTalkRobotNotifyBuilder custom() {
        return new DingTalkRobotNotifyBuilder();
    }

    public DingTalkRobotNotify build() {

        if (StringUtil.isBlank(robotAccessToken)) {
            // access token 不能为空
            throw new RuntimeException("ding-talk robot access token url not null");
        }

        if (StringUtil.isBlank(secret)) {
            // 安全签名不能为空
            throw new RuntimeException("ding-talk robot secret not null");
        }

        if (StringUtil.isBlank(dingTalkUrl)) {
            // 默认的钉钉群机器人推送url
            dingTalkUrl = DEFAULT_DING_TALK_URL;
        }

        if (null == httpClient) {
            // 默认的 http client 实现
            httpClient = HttpClientUtil.initHttpClient();
        }

        DingTalkRobotNotify dingTalkRobotNotify = new DingTalkRobotNotify(dingTalkUrl + robotAccessToken, secret, httpClient);
        return dingTalkRobotNotify;
    }

    public static void main(String[] args) {
        DingTalkRobotNotify dingTalkNotify = DingTalkRobotNotifyBuilder.custom()
                .setRobotAccessToken("2b03f8fa71d00beb3424e25afbae81ceb00d00a0b7eb6ba4979187bd2f7bc407")
                .setSecret("SEC4cfae557b9c464a04f73a284e697a1934b9e782d10a06783962ff3ee4e97ddb9")
                .setHttpClient(HttpClientUtil.initHttpClient())
                .build();
        DingTalkRobotMsgMarkdown dingTalkNotifyType = new DingTalkRobotMsgMarkdown();
        dingTalkNotifyType.setTitle("listen to me ！");
        dingTalkNotifyType.setText("the little yellow flower is floating in the air since the day of my birth");
        String result = dingTalkNotify.sendNotify(dingTalkNotifyType);
        System.out.println("result:" + result);
    }
}
